const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api/proxy',
    createProxyMiddleware({
      target: 'http://localhost:3000',
      changeOrigin: true,
      pathRewrite: {
        '^/api/proxy': '', // 移除 /api/proxy 前缀
      },
      router: function(req) {
        // 从查询参数中获取目标URL
        const targetUrl = new URL(req.url, 'http://localhost:3000').searchParams.get('url');
        return targetUrl || 'http://localhost:3000';
      },
      onProxyReq: function(proxyReq, req, res) {
        // 添加必要的请求头
        proxyReq.setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
        proxyReq.setHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8');
        proxyReq.setHeader('Accept-Language', 'zh-CN,zh;q=0.9,en;q=0.8');
        proxyReq.setHeader('Referer', 'https://www.bankofchina.com');
        proxyReq.setHeader('Cache-Control', 'no-cache');
      },
      onError: function(err, req, res) {
        res.writeHead(500, {
          'Content-Type': 'application/json',
        });
        res.end(JSON.stringify({ error: 'Proxy error: ' + err.message }));
      },
    })
  );
};